// ============================== 导入依赖 ============================== //

import CORE from '@login/CORE'
import TRANS from '@demo/CORE/UTIL/init/TRANS'
import store from '@/store'

import Vue from 'vue'
import API from './API'

const WS_PRE = process.env.VUE_APP_DEBUG_PORT ? CORE.PROXY.replace(/^http(s)?/, 'ws') : `ws://${location.host}`

const BTN_DICT = [
  ['ADD', 'Add'],
  ['UP', 'Add'],
  ['EDIT', 'Update'],
  ['PASS', 'Update'],
  ['REJ', 'Update'],
  ['DEL', 'Delete'],
]

// ============================== 导出初始化工具 ============================== //

export default {
  /**
   * 初始化仓库
   */
  initStore() {
    const CORE = this
    return {
      ...CORE.mixStore(store),
      created() {
        CORE.root = this
      },
    }
  },

  /**
   * 初始化内核
   */
  async initCORE() {
    // TOKEN 为空，不再继续
    if (!sessionStorage.TOKEN) {
      if (process.env.VUE_APP_DEBUG_PORT) { // 调试环境
        const password = await CORE.rsa('Admin123456')
        const { token } = await API.login({ account: 'admin', password, loginType: 1 }) // 默认登录
        sessionStorage.TOKEN = token // 记录 TOKEN
        location.reload() // 重载页面
      }
      return
    }

    // 开启遮罩
    this.loading()

    // 主题初始化
    this.themeInit()

    // 设置鉴权
    this.SOCKET.URL = `${WS_PRE}/ib/message/v1/websocket?labels=ib,admin,screen&uauth=${sessionStorage.TOKEN}`
    this.GRPC.META.authorization = `Bearer ${sessionStorage.TOKEN}`
    this.AXIOS.headers = () => ({ authorization: `Bearer ${sessionStorage.TOKEN}` })

    // 查询用户
    const USER = await API.getUser()
    this.USER = USER

    // 按钮权限
    BTN_DICT.forEach(([auth, btn]) => {
      const allTrue = USER.roleList.reduce((bool, role) => bool && role[`btn${btn}`] === 1, true) // 全 1 才 true
      this.MAP[`${this.MAP.AUTH_TYPE}_${auth}`] = allTrue
    })

    // 公共参数
    Vue.set(this.GRPC.COMMON_PARAM, 'tenantNo', USER.tenantNo)
    Vue.set(this.AXIOS.COMMON_PARAM, 'tenantNo', USER.tenantNo)

    // 多项查询
    const multi = [
      API.getDict(),
      API.getProperty(),
      API.getOrgan(),
      API.getRegion(),
      API.getDistrict(),
    ]
    const [DICT, PROPERTY, ORGAN, REGION, DISTRICT] = await Promise.all(multi)

    // 设置字典
    TRANS.transAllDict(this.DICT, DICT)
    TRANS.transAllProperty(this.DICT, PROPERTY)

    // 设置菜单
    const MENU = TRANS.transFilterMenu(USER.menuTree)
    this.MENU.TREE = TRANS.transTree(MENU)
    this.MENU.MAP = TRANS.transTreeMap({}, MENU)
    this.MENU.DICT = TRANS.transTreeDict([], MENU)
    this.MENU.NAME = TRANS.transAllName({}, this.MENU.MAP)
    this.MENU.ROUTE = TRANS.transMenuRoute({}, MENU)

    // 设置组织
    this.ORGAN.TREE = TRANS.transTree(ORGAN)
    this.ORGAN.MAP = TRANS.transTreeMap({}, ORGAN)
    this.ORGAN.DICT = TRANS.transTreeDict([], ORGAN)
    this.ORGAN.NAME = TRANS.transAllName({}, this.ORGAN.MAP)
    this.ORGAN.MY_TREE = USER.isAdmin ? this.ORGAN.TREE : TRANS.transMyTree(this.ORGAN.TREE, USER.organId)
    this.ORGAN.MY_MAP = TRANS.transTreeMap({}, this.ORGAN.MY_TREE)
    this.ORGAN.MY_DICT = TRANS.transTreeDict([], this.ORGAN.MY_TREE)

    // 设置区域
    this.REGION.TREE = TRANS.transTree(REGION)
    this.REGION.MAP = TRANS.transTreeMap({}, REGION)
    this.REGION.DICT = TRANS.transTreeDict([], REGION)
    this.REGION.NAME = TRANS.transAllName({}, this.REGION.MAP)
    this.REGION.MY_TREE = USER.isAdmin ? this.REGION.TREE : TRANS.transMyTree(this.REGION.TREE, USER.regionId)
    this.REGION.MY_MAP = TRANS.transTreeMap({}, this.REGION.MY_TREE)
    this.REGION.MY_DICT = TRANS.transTreeDict([], this.REGION.MY_TREE)

    // 设置省市区
    const [PROVINCE, CITY, AREA] = TRANS.transDictrict(DISTRICT)
    this.DISTRICT.TREE = TRANS.transTree(DISTRICT)
    this.DISTRICT.MAP = TRANS.transTreeMap({}, DISTRICT)
    this.DISTRICT.DICT = TRANS.transTreeDict([], DISTRICT)
    this.DISTRICT.NAME = TRANS.transAllName({}, this.DISTRICT.MAP)
    this.DISTRICT.PROVINCE = PROVINCE
    this.DISTRICT.CITY = CITY
    this.DISTRICT.AREA = AREA

    // 关闭遮罩
    this.unloading()
  },
}
